// my/pages/Mistake/Mistake.js
const wrongQuestionService = require('../../../utils/wrongQuestionService.js');
const storageUtil = require('../../../utils/storageUtil.js');

Page({
  data: {
    totalMistakes: 0,
    topTab: 'bySubject', // bySubject | all
    subjects: [], // 科目列表
    currentSubjectId: 0, // 0=全部
    currentType: 'all',
    chapterList: [],
    questionList: [],
    page: 1,
    pageSize: 10, // 减少每页数量，提升加载速度
    hasMore: true,
    loading: false,
    isLoadingMore: false, // 新增：是否正在加载更多
    checkedMap: {},
    isAllChecked: false
  },

  onLoad(options) {
    this.loadSubjects();
    this.loadBySubject(true);
    this.loadWrongQuestionCount();
    
    // 验证科目统计的准确性
    this.validateSubjectStatistics();
  },

  /**
   * 获取错题总数
   */
  async loadWrongQuestionCount() {
    try {
      const userId = storageUtil.getUserInfo()?.userId;
      if (!userId) {
        return;
      }
      
      // 获取当前科目的错题总数，而不是所有错题的总数
      const currentSubjectId = this.data.currentSubjectId;
      let totalCount = 0;
      
      if (currentSubjectId === 0) {
        // 全部科目：获取所有错题总数
        totalCount = await wrongQuestionService.getWrongQuestionCount(userId);
      } else {
        // 特定科目：获取该科目的错题总数
        totalCount = await wrongQuestionService.getWrongQuestionCountBySubject(userId, currentSubjectId);
      }
      
      this.setData({ totalMistakes: totalCount });
    } catch (error) {
      console.error('获取错题数量失败:', error);
      // 如果获取失败，使用当前列表的实际数量
      const currentCount = this.data.topTab === 'bySubject' ? this.data.chapterList.length : this.data.questionList.length;
      this.setData({ totalMistakes: currentCount });
    }
  },

  // 顶部tab
  onTopTab(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.topTab) return;
    this.setData({ topTab: id, page: 1, hasMore: true, checkedMap: {}, isAllChecked: false });
    if (id === 'bySubject') {
      this.loadBySubject(true);
    } else {
      this.loadAll(true);
    }
  },

  // 科目tab
  onSubjectTap(e) {
    const id = Number(e.currentTarget.dataset.id);
    if (id === this.data.currentSubjectId) return;
    this.setData({ currentSubjectId: id, page: 1, hasMore: true });
    this.loadBySubject(true);
    // 切换科目后重新获取总数
    this.loadWrongQuestionCount();
  },

  // 类型tab
  onTypeTap(e) {
    const id = e.currentTarget.dataset.id;
    if (id === this.data.currentType) return;
    this.setData({ currentType: id, page: 1, hasMore: true });
    if (this.data.topTab === 'all') this.loadAll(true);
  },

  onReachBottom() {
    if (!this.data.hasMore || this.data.loading || this.data.isLoadingMore) return;
    
    if (this.data.topTab === 'bySubject') {
      this.loadBySubject();
    } else {
      this.loadAll();
    }
  },

  // ===== 列表交互（与 myShouCang 底部一致） =====
  onCheckedChange(e) {
    const values = e.detail.value || [];
    const map = {};
    values.forEach(v => { map[v] = true; });
    const total = this.data.topTab === 'bySubject' ? this.data.chapterList.length : this.data.questionList.length;
    this.setData({ checkedMap: map, isAllChecked: values.length === total && total>0 });
  },
  
  onCheckOnly() {},
  
  onToggleAll() {
    const isAll = !this.data.isAllChecked;
    const map = {};
    const target = this.data.topTab === 'bySubject' ? this.data.chapterList : this.data.questionList;
    if (isAll) target.forEach(item => { map[item.id] = true; });
    this.setData({ isAllChecked: isAll, checkedMap: map });
  },
  
  async onDelete() {
    const ids = Object.keys(this.data.checkedMap);
    if (ids.length === 0) {
      wx.showToast({ title: '请选择', icon: 'none' });
      return;
    }
    
    // 显示确认弹窗
    wx.showModal({
      title: '确认删除',
      content: '确定要删除选中的错题吗？',
      confirmColor: '#E74C3C',
      success: async (res) => {
        if (res.confirm) {
          // 用户点击确定
          wx.showLoading({ title: '删除中...' });
          
          try {
            const success = await wrongQuestionService.deleteWrongQuestions(ids);
            if (success) {
              wx.showToast({ title: '删除成功', icon: 'success' });
              
              if (this.data.topTab === 'bySubject') {
                // 删除章节（逻辑删除）
                const remain = this.data.chapterList.filter(item => !this.data.checkedMap[item.id]);
                this.setData({ chapterList: remain, checkedMap: {}, isAllChecked: false });
              } else {
                // 删除单题（逻辑删除）
                const remain = this.data.questionList.filter(item => !this.data.checkedMap[item.id]);
                this.setData({ questionList: remain, checkedMap: {}, isAllChecked: false });
              }
              
              // 重新获取错题数量
              this.loadWrongQuestionCount();
            } else {
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
          } catch (error) {
            console.error('删除错题失败:', error);
            wx.showToast({ title: '删除失败', icon: 'none' });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },
  
  // 点击任何一条，进入做题页面
  onItemTap(e) {
    const id = e.currentTarget.dataset.id;
    const item = e.currentTarget.dataset.item;
    
    if (this.data.topTab === 'bySubject') {
      const realQuestionId = item.questionId || item.id;
      
      if (!realQuestionId) {
        wx.showToast({
          title: '题目ID无效',
          icon: 'none'
        });
        return;
      }
      
      const url = `/index/pages/questionAnalysis/questionAnalysis?questionId=${realQuestionId}`;
      
      wx.navigateTo({
        url: url,
        success: () => {
          console.log('跳转题目解析页面成功');
        },
        fail: (err) => {
          console.error('跳转题目解析页面失败:', err);
          wx.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    } else {
      const realQuestionId = item.questionId || item.id;
      
      if (!realQuestionId) {
        wx.showToast({
          title: '题目ID无效',
          icon: 'none'
        });
        return;
      }
      
      const url = `/index/pages/questionAnalysis/questionAnalysis?questionId=${realQuestionId}`;
      
      wx.navigateTo({
        url: url,
        success: () => {
          console.log('跳转题目解析页面成功');
        },
        fail: (err) => {
          console.error('跳转题目解析页面失败:', err);
          wx.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    }
  },

  // ===== 数据加载（对接后端接口） =====
  async loadSubjects() {
    try {
      const subjects = await wrongQuestionService.getSubjects();
      if (subjects && subjects.length > 0) {
        this.setData({ subjects });
      } else {
        const defaultSubjects = [
          { id: 1, name: '物理', icon: '/images/wuli.png' },
          { id: 2, name: '科学', icon: '/images/kexue.png' },
          { id: 3, name: '化学', icon: '/images/huaxue.png' },
          { id: 4, name: '生物', icon: '/images/shengwu.png' },
          { id: 5, name: '数学', icon: '/images/shuxue.png' },
          { id: 6, name: '政治', icon: '/images/zhengzhi.png' },
          { id: 7, name: '文学', icon: '/images/wenxue.png' }
        ];
        this.setData({ subjects: defaultSubjects });
      }
    } catch (error) {
      console.error('获取科目列表失败:', error);
      const defaultSubjects = [
        { id: 1, name: '物理', icon: '/images/wuli.png' },
        { id: 2, name: '科学', icon: '/images/kexue.png' },
        { id: 3, name: '化学', icon: '/images/huaxue.png' },
        { id: 4, name: '生物', icon: '/images/shengwu.png' },
        { id: 5, name: '数学', icon: '/images/shuxue.png' },
        { id: 6, name: '政治', icon: '/images/zhengzhi.png' },
        { id: 7, name: '文学', icon: '/images/wenxue.png' }
      ];
      this.setData({ subjects: defaultSubjects });
    }
  },

  async loadBySubject(reset = false) {
    const { page, pageSize, currentSubjectId } = this.data;
    
    if (reset) {
      this.setData({ loading: true, page: 1 });
    } else {
      this.setData({ isLoadingMore: true });
    }
    
    try {
      const userId = storageUtil.getUserInfo()?.userId;
      if (!userId) {
        this.setData({ 
          chapterList: [],
          loading: false,
          isLoadingMore: false,
          hasMore: false
        });
        return;
      }

      const params = {
        pageNum: reset ? 1 : page,
        pageSize: pageSize,
        userId: userId
      };
      
      const questions = await wrongQuestionService.getAllWrongQuestions(params);
      
      if (questions && questions.length > 0) {
        const processedQuestions = questions.map(item => {
          let subjectId = item.subjectId;
          
          if (!subjectId && item.questionBank) {
            subjectId = wrongQuestionService.assignSubjectByBankId(
              item.questionBank.id || item.questionBankId, 
              item.questionBank.name
            );
          }
          if (!subjectId) {
            subjectId = wrongQuestionService.assignSubjectByBankId(
              item.questionBankId, 
              item.questionBankName
            );
          }
          
          return {
            id: item.id || item.questionId,
            questionId: item.questionId || item.question?.id || item.id,
            thumb: item.coverImage || item.question?.coverImage || this.getSubjectIcon(subjectId),
            title: item.title || item.question?.title || item.questionTitle || `错题 ${item.id}`,
            time: this.formatTime(item.lastWrongTime || item.createTime),
            subjectId: subjectId,
            categoryName: this.getSubjectName(subjectId),
            mistakeCount: 1,
            originalData: item
          };
        });

        let filteredQuestions = processedQuestions;
        if (currentSubjectId !== 0) {
          filteredQuestions = processedQuestions.filter(item => {
            const itemSubjectId = Number(item.subjectId);
            const targetSubjectId = Number(currentSubjectId);
            return itemSubjectId === targetSubjectId;
          });
        }

        const newList = reset ? filteredQuestions : this.data.chapterList.concat(filteredQuestions);
        const nextPage = reset ? 2 : page + 1;
        const hasMore = filteredQuestions.length === pageSize;
        
        this.setData({
          chapterList: newList,
          page: nextPage,
          hasMore: hasMore,
          loading: false,
          isLoadingMore: false
        });
      } else {
        this.setData({
          chapterList: reset ? [] : this.data.chapterList,
          loading: false,
          isLoadingMore: false,
          hasMore: false
        });
      }
    } catch (error) {
      console.error('获取按科目错题数据失败:', error);
      this.setData({
        chapterList: reset ? [] : this.data.chapterList,
        loading: false,
        isLoadingMore: false,
        hasMore: false
      });
    }
  },

  async loadAll(reset = false) {
    const { page, pageSize } = this.data;
    
    if (reset) {
      this.setData({ loading: true, page: 1 });
    } else {
      this.setData({ isLoadingMore: true });
    }
    
    try {
      const userId = storageUtil.getUserInfo()?.userId;
      if (!userId) {
        this.setData({ 
          questionList: [],
          loading: false,
          isLoadingMore: false,
          hasMore: false
        });
        return;
      }

      const params = {
        pageNum: reset ? 1 : page,
        pageSize: pageSize,
        userId: userId
      };

      const questions = await wrongQuestionService.getAllWrongQuestions(params);
      
      if (questions && questions.length > 0) {
        const processedQuestions = questions.map(item => {
          let subjectId = item.subjectId;
          
          if (!subjectId && item.questionBank) {
            subjectId = wrongQuestionService.assignSubjectByBankId(
              item.questionBank.id || item.questionBankId, 
              item.questionBank.name
            );
          }
          if (!subjectId) {
            subjectId = wrongQuestionService.assignSubjectByBankId(
              item.questionBankId, 
              item.questionBankName
            );
          }
          
          return {
            id: item.id || item.questionId,
            questionId: item.questionId || item.question?.id || item.id,
            thumb: item.coverImage || item.question?.coverImage || this.getSubjectIcon(subjectId),
            title: item.title || item.question?.title || item.questionTitle || `错题 ${item.id}`,
            time: this.formatTime(item.lastWrongTime || item.createTime),
            subjectId: subjectId,
            categoryName: this.getSubjectName(subjectId),
            originalData: item
          };
        });

        const newList = reset ? processedQuestions : this.data.questionList.concat(processedQuestions);
        const nextPage = reset ? 2 : page + 1;
        const hasMore = processedQuestions.length === pageSize;
        
        this.setData({
          questionList: newList,
          page: nextPage,
          hasMore: hasMore,
          loading: false,
          isLoadingMore: false
        });
      } else {
        this.setData({
          questionList: reset ? [] : this.data.questionList,
          loading: false,
          isLoadingMore: false,
          hasMore: false
        });
      }
    } catch (error) {
      console.error('获取所有错题数据失败:', error);
      this.setData({
        questionList: reset ? [] : this.data.questionList,
        loading: false,
        isLoadingMore: false,
        hasMore: false
      });
    }
  },

  // 根据科目ID获取科目图标
  getSubjectIcon(subjectId) {
    const subjectMap = {
      1: '/images/wuli.png',
      2: '/images/kexue.png',
      3: '/images/huaxue.png',
      4: '/images/shengwu.png',
      5: '/images/shuxue.png',
      6: '/images/zhengzhi.png',
      7: '/images/wenxue.png'
    };
    return subjectMap[subjectId] || '/images/题库.png';
  },

  // 根据科目ID获取科目名称
  getSubjectName(subjectId) {
    const subjectMap = {
      1: '物理',
      2: '科学',
      3: '化学',
      4: '生物',
      5: '数学',
      6: '政治',
      7: '文学'
    };
    return subjectMap[subjectId] || '未知科目';
  },

  // 格式化时间
  formatTime(time) {
    if (!time) return '';
    const date = new Date(time);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  /**
   * 验证科目统计的准确性
   */
  async validateSubjectStatistics() {
    try {
      const userId = storageUtil.getUserInfo()?.userId;
      if (!userId) return;
      
      // 获取所有错题
      const allQuestions = await wrongQuestionService.getAllWrongQuestions({
        userId: userId,
        pageNum: 1,
        pageSize: 1000
      });
      
      if (!allQuestions || allQuestions.length === 0) return;
      
      // 按科目统计
      const subjectStats = {};
      allQuestions.forEach(item => {
        let subjectId = item.subjectId || item.questionBank?.subjectId;
        if (!subjectId) {
          subjectId = wrongQuestionService.assignSubjectByBankId(
            item.questionBankId, 
            item.questionBank?.name
          );
        }
        
        if (!subjectStats[subjectId]) {
          subjectStats[subjectId] = 0;
        }
        subjectStats[subjectId]++;
      });
      
      console.log('科目统计验证:', {
        totalQuestions: allQuestions.length,
        subjectStats: subjectStats,
        totalBySubjects: Object.values(subjectStats).reduce((sum, count) => sum + count, 0)
      });
      
      // 检查总数是否一致
      const totalBySubjects = Object.values(subjectStats).reduce((sum, count) => sum + count, 0);
      if (totalBySubjects !== allQuestions.length) {
        console.warn('科目统计总数不一致！', {
          totalQuestions: allQuestions.length,
          totalBySubjects: totalBySubjects
        });
      }
      
    } catch (error) {
      console.error('验证科目统计失败:', error);
    }
  }
});